<?php

namespace app\api\controller;

use app\common\model\Clients as M;
use think\Exception;

class Registers extends Base
{

    /**
     * 注册
     * @return \type
     */
    public function add()
    {

        $data = input('post.');

        $result = $this->validate($data, 'app\api\validate\Registers');
        if (true !== $result) {
            return js_return(0, $result);
        }

        $openid   = $this->getWXOpenid();
        $userInfo = $this->getWXData();
        if (empty($openid)) {
            return js_return(0, '无效数据,未获取微信ID');
        }

        $m    = new M();
        $user = $m->getByOpenid($openid);
        if ($user) {
            return js_return(2, '已有用户',$user);
        }

        $userInfo = $this->getWXData();


        try {

            $storeData = json_decode($userInfo, true);

            //推荐人信息
            $parent_code = input('post.parent_code');
            if ($parent_code && ($parent_client = $m->getByReftoken($parent_code))) {
                $storeData['ref_id']       = $parent_client['id'];
                $storeData['company_id']   = $parent_client['company_id'];
                $storeData['company_name'] = $parent_client['company_name'];
                $storeData['is_bind'] = 1;
            }
            else {
                $storeData['ref_id'] = 0;
            }


            $storeData['openid']     = $openid;
            $storeData['ref_token']  = unique($openid);
            $storeData['last_time']  = T();
            $storeData['create_at']  = T();
            $storeData['nickname']   = $storeData['nickName'];
            $storeData['avatar_url'] = $storeData['avatarUrl'];

            $s = $m->save($storeData);

            if ($s) {
                $client = $m->getByOpenid($openid);
                return js_return(1, 'success', $this->makeWXData($client));
            }
            return js_return(0, 'insert failed');
        } catch (Exception $e) {

            return js_return(0, $e->getMessage());
        }
    }

}
